package com.example.zhunongzonghe.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhunongzonghe.beans.ZnCollectFarmBean;
import com.example.zhunongzonghe.beans.ZnFarmSpecificationBean;
import com.example.zhunongzonghe.beans.ZnFarmproduceBean;
import com.example.zhunongzonghe.dao.ZnCollectFarmMapper;
import com.example.zhunongzonghe.dao.ZnFarmproduceMapper;
import com.example.zhunongzonghe.entity.ZnCollectFarm;
import com.example.zhunongzonghe.entity.ZnFarmSpecification;
import com.example.zhunongzonghe.entity.ZnFarmproduce;
import com.example.zhunongzonghe.entity.ZnUsers;
import com.example.zhunongzonghe.enums.FarmCollectStatusEnum;
import com.example.zhunongzonghe.service.IZnUsersService;
import com.example.zhunongzonghe.service.ZnCollectFarmService;
import com.example.zhunongzonghe.service.ZnFarmSpecificationService;
import com.example.zhunongzonghe.utils.BeanCopyUtils;
import com.example.zhunongzonghe.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
* @author 蔡某人
* @description 针对表【zn_collect_farm】的数据库操作Service实现
* @createDate 2024-04-09 23:57:18
*/
@Service
public class ZnCollectFarmServiceImpl extends ServiceImpl<ZnCollectFarmMapper, ZnCollectFarm>
    implements ZnCollectFarmService{

    @Resource
    private RedisCache redisCache;
    @Resource
    private IZnUsersService znUsersService;
    @Resource
    private ZnCollectFarmMapper znCollectFarmMapper;
    @Resource
    private ZnFarmproduceMapper farmproduceMapper;
    @Resource
    private ZnFarmSpecificationService specificationService;

    private static final String FARM_COLLECT_KEY = "farm_collect";//hash前缀
    private static final String FARM_COLLECT_COUNT_KEY = "farm_collect_count";//收藏总数前缀
    private static final String FARM_COLLECT_DETAIL_KEY = "farm_collect_detail";//收藏状态

    @Override
    public void addCollect(ZnCollectFarmBean znCollectFarmBean, String userName) {
        ZnUsers znUsers = znUsersService.getUserName(userName);
        Integer farmId = znCollectFarmBean.getFarmId();
        Integer userId = znUsers.getId();
        Integer status = znCollectFarmBean.getCollectStatus();
        //与redis做交互的Hash的key
        String collectHashKey = collectHashKey(farmId.toString(),userId.toString());
        redisCache.setCacheHashValue(FARM_COLLECT_KEY,collectHashKey,status);
        String detailKey = FARM_COLLECT_DETAIL_KEY+"."+farmId+"."+userId;//被谁点过赞的key
        String countKey = FARM_COLLECT_COUNT_KEY+"."+farmId;
        if (FarmCollectStatusEnum.COLLECT.getCode() == status){
            redisCache.increment(countKey,1);//收藏时加1
            redisCache.setCacheObject(detailKey,"1");
        }else {
            Integer count =redisCache.getInt(countKey);
            if (Objects.isNull(count) || count<0){
                return;
            }
            redisCache.increment(countKey,-1);//取消收藏时-1
            redisCache.deleteObject(detailKey);
        }
    }

    @Override
    public Boolean isCollect(Integer farmId, Integer userId) {
        String detailKey = FARM_COLLECT_DETAIL_KEY+"."+farmId+"."+userId;//被谁点过收藏的key
        return redisCache.exist(detailKey);//获取redis内的detailKey，如果存在说明当前用户收藏过该帖子
    }

    @Override
    public Integer CollectCounts(Integer farmId) {
        String countKey = FARM_COLLECT_COUNT_KEY+"."+farmId;
        Integer count =redisCache.getInt(countKey);
        if (Objects.isNull(count) || count<0){
            return 0;
        }
        return redisCache.getInt(countKey);
    }

    @Override
    public void syncFarmCollect() {
        Map<Object,Object> farmCollectMap = redisCache.getHashAndDelete(FARM_COLLECT_KEY);
        if (MapUtil.isEmpty(farmCollectMap)){
            return;
        }
        //批量同步到数据库
        List<ZnCollectFarm> znCollectFarms = new ArrayList<>();
        farmCollectMap.forEach((key,value) ->{
            ZnCollectFarm znCollectFarm = new ZnCollectFarm();
            String[] keyArr = key.toString().split(":");
            String postId = keyArr[0];
            String UserId = keyArr[1];
            znCollectFarm.setFarmId(Integer.valueOf(postId));
            znCollectFarm.setUserId(Integer.valueOf(UserId));
            znCollectFarm.setCollectStatus((Integer) value);
            znCollectFarm.setCreateTime(LocalDateTime.now());
            znCollectFarm.setUpdateTime(LocalDateTime.now());
            znCollectFarms.add(znCollectFarm);
        });
        znCollectFarmMapper.insertList(znCollectFarms);
    }

    @Override
    public void delRepetition() {

    }

    @Override
    public Page<ZnFarmproduceBean> MyCollects(String username, Integer currentPage, Integer pageSize) {
        ZnUsers znUsers = znUsersService.getUserName(username);
        String key = FARM_COLLECT_KEY+"*"+znUsers.getId();
        Collection<String> keys = redisCache.keys(key);
        if (keys==null) return null;
        List<ZnFarmproduceBean> beanList = new ArrayList<>();
        for (String stringKey: keys
        ) {
            String[] parts = stringKey.split("\\."); // 使用 "." 分割字符串
            String farmId = parts[1]; // 第二部分即为 "21"
            Page<ZnFarmproduce> page = new Page<>(currentPage,pageSize);
            LambdaQueryWrapper<ZnFarmproduce> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZnFarmproduce::getFarmId,farmId);
            Page<ZnFarmproduce> postPage = farmproduceMapper.selectPage(page,queryWrapper);
            for (ZnFarmproduce znfarm: postPage.getRecords()
            ) {
                ZnFarmproduceBean farmBean = new ZnFarmproduceBean();
                LambdaQueryWrapper<ZnFarmSpecification> specWrapper = new LambdaQueryWrapper<>();
                specWrapper.eq(ZnFarmSpecification::getZnFarmId,znfarm.getFarmId());
                List<ZnFarmSpecification> specificationList = specificationService.list(specWrapper);
                List<ZnFarmSpecificationBean> beans =
                        BeanCopyUtils.copyBeanList(specificationList,ZnFarmSpecificationBean.class);
                farmBean.setSpecificationBeans(beans);
                farmBean.setCollectOrNot(isCollect(znfarm.getFarmId(),znUsers.getId()));
                farmBean.setCollectCount(CollectCounts(znfarm.getFarmId()));
                BeanUtils.copyProperties(znfarm,farmBean);
                beanList.add(farmBean);
            }
        }
        Page<ZnFarmproduceBean> resultPage = new Page<>();
        resultPage.setRecords(beanList);
        resultPage.setSize(beanList.size());
        resultPage.setTotal(beanList.size());
        resultPage.setCurrent(currentPage);
        return resultPage;
    }

    private String collectHashKey(String farmId,String userId){
        return farmId + ":" +userId;
    }
}




